from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from .models import *
import jwt
from meiduo.settings import SECRET_KEY
from rest_framework.response import Response
# Create your views here.
class LoginView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        print(username)
        print(password)
        user = UserModel.objects.filter(username=username,password=password).first()
        if user:
            info={
                'uid':user.id,
                'username':user.username
            }
            token = jwt.encode(info,SECRET_KEY)
            return Response({'msg': '登陆成功', "token":token})
        else:
            return Response({'msg':'登陆失败'}, status=401)

def mytest(func):
    def inner(request):
        print('-------在类视图方法调用前执行--------')
        token = request.META.get('HTTP_AUTHORIZATION')
        print(token)
        try:
            s = jwt.decode(token, SECRET_KEY)
            user_id = s.get('user_id')
        except Exception as e:
            print(e)
            user_id = None
        request.COOKIES['user_id'] = user_id
        return func(request)

    return inner


from django.utils.decorators import method_decorator


# 这是测试接口
@method_decorator(mytest, name='dispatch')
class TestViews(APIView):
    def get(self, request):
        print('执行装饰器之后调用get接口')
        user_id = request.COOKIES.get('user_id')
        if user_id:
            return Response({'msg': '令牌有效'})
        else:
            return Response({'msg': '令牌无效'})

    def post(self, request):
        print('执行装饰器之后调用post接口')
        user_id = request.COOKIES.get('user_id')
        if user_id:
            return Response({'msg': '令牌有效'})
        else:
            return Response({'msg': '令牌无效'})